package com.ruoyi.teaching.controller;

import com.ruoyi.teaching.domain.Student;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class ExportController {
    /**
     * 1.查询业务所需数据
     * 2.封装到map(或者业务对象)中
     * 3.指定模板与导出文件名称
     * 4.响应设置 不设置会导致乱码 文件格式出错等问题
     * 5.模板配置
     * 6.变量替换
     * 7.文件输出
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        Map<String, Object> model = new HashMap<>(4);
        //要与ftl中的对象一致
        model.put("student",new Student(1L,"andy","唐僧",1));
        model.put("scoreList", Arrays.asList("80", "90", "60", "80", "85","90","80"));
        // 指定FreeMarker模板文件的位置
        String templateFilePath = "学员学习跟进月表.xml";
        String excelName = "张三学习跟进月表" + ".xlsx";

        FileInputStream inputStream = null;
        ServletOutputStream outputStream = null;
        File file = null;
        // 使用FreeMarker加载模板文件
        try {
            // 重置响应
            response.reset();
            // 设置响应头部，指定为附件形式，并指定文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName, "UTF8"));
            // 设置响应字符编码为UTF-8
            response.setCharacterEncoding("utf-8");
            // 设置响应内容类型为Excel
            response.setContentType("application/vnd.ms-excel;charset=utf-8");

            // 创建FreeMarker配置对象
            Configuration cfg = new Configuration(Configuration.getVersion());
            // 指定FreeMarker模板文件的位置
            String path = "/templates/";
            cfg.setClassForTemplateLoading(getClass(), path);
            // 获取指定路径下的模板文件
            Template template = cfg.getTemplate(templateFilePath);

            file = new File(excelName);
            FileWriter out = new FileWriter(excelName);
            // 变量替换
            template.process(model, out);

            // 将文件输出到response,返回给客户端
            inputStream = new FileInputStream(file);
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            inputStream.close();

            outputStream = response.getOutputStream();
            outputStream.write(buffer);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            log.error("导出失败", e);
            throw new RuntimeException(e);
        }
    }
}

